﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.UI.WebControls;

namespace Microsoft.JCI.Common.Utility
{
    public static class FileUploadExtension
    {
        public static UploadFileBaseInfo UploadFile(this FileUpload fuFileUpload, string Path)
        {
            UploadFileBaseInfo info = new UploadFileBaseInfo();
            if (fuFileUpload.PostedFile == null || string.IsNullOrEmpty(fuFileUpload.PostedFile.FileName))
            {
                info.Message = "请选择上传文件";
                info.IsSuccess = false;
                return info;
            }

            const int maxLength = 1024 * 1024 * 4; //最大4M，否则内存占用太严重,需要让用户自己拆分文件
            if (fuFileUpload.FileBytes.Length < 0 || fuFileUpload.FileBytes.Length > maxLength)
            {
                info.Message = "上传文件大小应在4M内";
                info.IsSuccess = false;
                return info;
            }

            info.FileOriginalName = System.IO.Path.GetFileName(fuFileUpload.PostedFile.FileName);
            info.FileExtension = System.IO.Path.GetExtension(info.FileOriginalName);
            info.FileName = string.Concat(System.IO.Path.GetFileName(fuFileUpload.PostedFile.FileName), "_", DateTime.Now.ToFileTime());
            info.FileContentType = fuFileUpload.PostedFile.ContentType;
            //if (System.IO.Path.GetExtension(info.FileOriginalName) != ".xls")
            //{
            //    info.IsSuccess = false;
            //    info.Message = "只能上传Excel文件";
            //    return info;
            //}
            info.FileSize = fuFileUpload.FileBytes.Length;

            string physicalPath = "";

            //physicalPath = HttpContext.Current.Server.MapPath(Path);
            physicalPath = Path;

            //将上传的文件保存到文件服务器磁盘
            if (!Directory.Exists(physicalPath))
            {
                Directory.CreateDirectory(physicalPath);
            }
            physicalPath = System.IO.Path.Combine(physicalPath, info.FileName);
            info.FilePath = physicalPath;
            fuFileUpload.SaveAs(physicalPath);
            info.IsSuccess = true;

            return info;
        }
    }
}
